<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>H5Player</title>
    <script src="h5player.js"></script>
    <style>
        .root {
            display: flex;
            place-content: center;
            margin-top: 3rem;
        }
        .container-shell {
            backdrop-filter: blur(5px);
            background: hsla(0, 0%, 50%, 0.5);
            padding: 30px 4px 10px 4px;
            width: auto;
            position: relative;
            border-radius: 5px;
            box-shadow: 0 10px 20px;
        }
        .container-shell:before {
            content: "H5 demo player";
            position: absolute;
            color: darkgray;
            top: 4px;
            left: 10px;
            text-shadow: 1px 1px black;
        }
        #container {
            background: rgba(13, 14, 27, 0.7);
            width: 640px;
            height: 398px;
        }
        .input {
            display: flex;
            margin-top: 10px;
            color: white;
        }
        .input input {
            flex: auto;
            margin-right: 10px;
        }
        .input label {
            width: 100px;
            text-align: left;
            margin-left: 10px;
        }
        .option span {
            color: white;
        }
        .page {
            background-color: #ffffff;
            color: #fff;
            font-family: sans-serif;
            background-repeat: no-repeat;
            background-position: top;
        }
        @media (max-width: 720px) {
            #container {
                width: 90vw;
                height: 52.7vw;
            }
        }
    </style>
</head>
<body class="page">
<div class="root">
    <div class="container-shell">
        <div id="container"></div>
        <div class="input" style="width: 640px">
            1.优先支持MSE硬解，支持低延迟与追帧消延迟 <br>
            2.分辨率（≤720p），码率（≤1Mbps），帧率（≤15FPS），客户端CPU（≥4核），H265格式的视频采用wasm软解<br>
            3.分辨率（≥1080p），码率（≥2Mbps），帧率（≥30FPS），H265格式的视频由GPU服务器转换成H264格式后使用MSE硬解<br>
        </div>
        <div class="input">
            <label for="baseUrl">baseUrl：</label>
            <input type="text" id="baseUrl" value="http://localhost:9090/invms8100/apploginVideo">
        </div>
        <div class="input">
            <label for="userName">用户名：</label>
            <input type="text" id="userName" value="bwgc">
            <label for="password">密码：</label>
            <input type="text" id="password" value="Bwgc@123">
        </div>
        <div class="input">
            <label for="camera">摄像机编号：</label>
            <input type="text" id="camera" value="34010000001323426228">
        </div>
        <div class="input">
            <button id="play">播放</button>
            <button id="pause" style="display: none">暂停</button>
            <button id="destroy">销毁</button>
        </div>
    </div>
</div>
<script>
    let $player = document.getElementById('play');
    let $pause = document.getElementById('pause');
    let $container = document.getElementById('container');
    let $destroy = document.getElementById('destroy');
    let $baseUrl = document.getElementById('baseUrl');
    let $userName = document.getElementById('userName');
    let $password = document.getElementById('password');
    let $camera = document.getElementById('camera');

    let showOperateBtns =true;
    let h5player = null;
    let inviteId = null;
    let heartbeatTimer = null;

    function create() {
        h5player = new H5Player({
            container: $container,
            videoBuffer: 0.2,
            isResize: false,
            text: "",
            loadingText: "加载中...",
            debug: true,
            isFlv: true,
            showBandwidth: showOperateBtns,
            operateBtns: {
                fullscreen: showOperateBtns,
                screenshot: showOperateBtns,
                play: showOperateBtns,
                audio: showOperateBtns,
                record: showOperateBtns,
            },
            useMSE: true
        });

        h5player.onLog = msg => console.error(msg);
        h5player.onRecord = (status) => console.log('onRecord', status);
        h5player.onPause = () => console.log('onPause');
        h5player.onPlay = () => console.log('onPlay');
        h5player.onFullscreen = msg => console.log('onFullscreen', msg);
        h5player.onMute = msg => console.log('onMute', msg);
        $player.style.display = 'inline-block';
        $pause.style.display = 'none';
        $destroy.style.display = 'none';
    }

    create();

    $player.addEventListener("click", async () => {
        let href = await getPlayUrl();
        if (href) {
            h5player.play(href);
            $player.style.display = 'none';
            $pause.style.display = 'inline-block';
            $destroy.style.display = 'inline-block';
            startHeartbeat();
        }
    }, false);


    $pause.addEventListener('click', function () {
        $player.style.display = 'inline-block';
        $pause.style.display = 'none';
        h5player.pause();
    })

    $destroy.addEventListener('click', function () {
        stopVideo();

        if (h5player) {
            h5player.destroy().then(()=>{
                create();
            });
        }
        else {
            create();
        }
    })

    async function getPlayUrl() {
        const reqUrl = $baseUrl.value + "/queryVideoUrl.action?signName=" + $userName.value + "&userPwd=" + $password.value + "&protocolType=8&streamType=0&cameraId=" + $camera.value + "&clientSN=111'";
        console.log("Http request: ", reqUrl)
        const res = await fetch(reqUrl);
        let jsonData = await res.json();
        const { code, msg } = jsonData;
        if (code < 0) {
            alert("Play failed: " + msg);
            return "";
        }

        const playUrl = jsonData.data.videoStream;
        inviteId = jsonData.data.inviteId;
        console.log("Http response, play url: ", playUrl, ", invite id: " + inviteId);

        // 设置 video 播放源
        //ws://192.168.0.96:9205/vod/3.live.mp4
        const urlObj = new URL(playUrl);
        let stream = urlObj.searchParams.get('id');
        if (stream === '') {
            stream = urlObj.searchParams.get('session');
        }

        let url = "ws://192.168.0.96:" + urlObj.port + "/api/v1/h5swsapi?token=token1&profile=main&session=" + stream;
        if (true === this.p) {
            console.log("====" + url + "-----------");
        }

        return url;
    }

    async function stopVideo() {
        // 调用关闭接口
        try {
            const stopUrl = $baseUrl.value + "/closeVideo.action?inviteId=" + inviteId;
            console.log("stopUrl", stopUrl)
            await fetch(stopUrl, { method: 'POST' });
            stopHeartbeat();
            inviteId = null;
        } catch (err) {
            console.error('Close video failed: ', err);
        }
    }

    //启动心跳
    function startHeartbeat() {
        if (heartbeatTimer) return;
        heartbeatTimer = setInterval(() => {
            const heartbeatUrl = baseUrl.value + "/resetHeartTime.action?clientSN=111";
            fetch(heartbeatUrl, { method: 'POST'}).catch(err => console.warn('心跳失败', err));
        }, 15000);
    }

    //停止心跳
    function stopHeartbeat() {
        if (heartbeatTimer) {
            clearInterval(heartbeatTimer);
            heartbeatTimer = null;
        }
    }

</script>
</body>
</html>
